package com.iseastar.guojiang.loc;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.Message;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.iseastar.guojiang.consts.AppConfig;
import com.iseastar.guojiang.consts.MsgID;

import droid.frame.activity.HandlerMgr;

/**
 * 定位服务<br>
 * xmpp心跳的时候会启动该定位服务，定位服务成功以后会上报当前位置至服务器端<br>
 * 每天晚上xmpp服务结束的时候结束该服务
 * 
 * @author coffee<br>
 *         2015-4-24上午10:29:17
 */
public class BaiduLocationService extends Service implements BDLocationListener {

	// 定位相关
	private LocationClient mLocClient;
	//
	public static boolean isStarted = false;
	private int msgId = -1;

	@Override
	public void onCreate() {
		super.onCreate();
		// 定位初始化
		mLocClient = new LocationClient(this);
		mLocClient.registerLocationListener(this);
		LocationClientOption option = new LocationClientOption();
		option.setIsNeedAddress(true);// 设置以后,请求结果 BDLocation#getCity 就不为null了
		option.setOpenGps(true);// 打开gps
		option.setCoorType("bd09ll"); // 设置坐标类型
		option.setScanSpan(AppConfig.getBadiuLocBeat());// 定位频率
		mLocClient.setLocOption(option);
		mLocClient.start();
		//
		isStarted = true;
	}

	@Override
	public IBinder onBind(Intent intent) {

		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		if (intent != null) {
			msgId = intent.getIntExtra("msgId", -1);
		}
		// 刷新定位
		mLocClient.requestLocation();
		//
		return super.onStartCommand(intent, flags, startId);
	}

	/**
	 * 定位SDK监听函数
	 */

	@Override
	public void onReceiveLocation(final BDLocation location) {
		Message msg = Message.obtain();
		if (msgId == -1) {
			msg.what = MsgID.location_baidu;
		} else {
			msg.what = msgId;
			msgId = -1;// reset
		}
		msg.obj = location;
		HandlerMgr.sendMessage(msg, 0);
		//
		// int userId = ((BeeApplication) getApplication()).getUser().getId();
		// AppHttp.getInstance().beat(userId, location.getLatitude(), location.getLongitude());
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		// 退出时销毁定位
		mLocClient.stop();
		//
		isStarted = false;
	}

}
